home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / find_cryst < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  31.4 KB  |  875 lines

  1. #!/usr/local/bin/gawk -f
  2. #!/usr/bin/awk -f
  3. # @(#) find_cryst.gawk 1.2 97/01/06
  4. # 93/03/20 john h. dubois iii (john@armory.com)
  5. # 93/07/02 Added help & sorting
  6. # 94/03/09 Use gawk so - options can be given.
  7. # 97/01/06 Use ProcArgs lib
  8. BEGIN {
  9.     Name = "find_cryst"
  10.     Usage = "Usage: " Name " [-hs] desired min max [step]\n"
  11.     ARGC = Opts(Name,Usage,"hs",3)
  12.     if ("h" in Options) {
  13.     printf \
  14. "%s: find a crystal that can be divided down as close as possible\n"\
  15. "to a desired frequency.\n"\
  16. Usage \
  17. "desired is the desired frequency.  min and max are two crystal frequencies.\n"\
  18. "For each integer value between them, the two divisors that bring the\n"\
  19. "crystal frequency closest to the desired frequency are determined,\n"\
  20. "and the divisor and the resulting frequencies and errors are printed.\n"\
  21. "If step is given, every step'th integer between min and max is checked.\n"\
  22. "If -s is given, the results are sorted by error percentage.\n",Name
  23.     exit(0)
  24.     }
  25.     Sort = "s" in Options
  26.     Desired = ARGV[1]
  27.     Min = ARGV[2]
  28.     Max = ARGV[3]
  29.     if (ARGC > 4)
  30.     Step = ARGV[4]
  31.     else
  32.     Step = 1
  33.     Format = "%8s  %7s  %8s  %6s  %7s  %8s  %6s"
  34.     printf \
  35.     Format "\n","Freq","Divisor","DivFreq","%Err","Divisor","DivFreq","%Err"
  36.     n = 0
  37.     for (i = Min; i <= Max; i += Step) {
  38.     divisor = int(i / Desired)
  39.     LowFreq = i / (divisor+1)
  40.     HighFreq = i / divisor
  41.     LowErr = Error(Desired,LowFreq)
  42.     HighErr = Error(Desired,HighFreq)
  43.     Result = sprintf(Format,i,divisor+1,LowFreq,sprintf("%5.2f",LowErr),
  44.     divisor,HighFreq,sprintf("%5.2f",HighErr))
  45.     if (Sort) {
  46.         Res[++n] = Result
  47.         Errs[n] = min(abs(LowErr),abs(HighErr))
  48.     }
  49.     else
  50.         print Result
  51.     }
  52.     if (Sort) {
  53.     qsortArbIndByValue(Errs,k)
  54.     for (i = 1; i <= n; i++) {
  55.         print Res[k[i]]
  56.     }
  57.     }
  58. }
  59.  
  60. # returns the % of a that b is away from it
  61. function Error(a,b) {
  62.     return ((b - a) / a)*100
  63. }
  64.  
  65. function abs(a) {
  66.     return a < 0 ? -a : a
  67. }
  68.  
  69. function min(a,b) {
  70.     if (a < b)
  71.     return a
  72.     else
  73.     return b
  74. }
  75.  
  76. ### Begin qsort routines
  77.  
  78. # Arr[] is an array of values with arbitrary indices.
  79. # k[] is returned with numeric indices 1..n.
  80. # The values in k[] are the indices of Arr[],
  81. # ordered so that if Arr[] is stepped through
  82. # in the order Arr[k[1]] .. Arr[k[n]], it will be stepped
  83. # through in order of the values of its elements.
  84. # The return value is the number of elements in the arrays (n).
  85. function qsortArbIndByValue(Arr,k,  ArrInd,ElNum) {
  86.     ElNum = 0
  87.     for (ArrInd in Arr)
  88.     k[++ElNum] = ArrInd
  89.     qsortSegment(Arr,k,1,ElNum)
  90.     return ElNum
  91. }
  92.  
  93. # Sort a segment of an array.
  94. # Arr[] contains data with arbitrary indices.
  95. # k[] has indices 1..nelem, with the indices of arr[] as values.
  96. # This function sorts the elements of arr that are pointed to by
  97. # k[start..end], swapping the values of elements of k[] so that
  98. # when this function returns arr[k[start..end]] will be in order.
  99. function qsortSegment(Arr,k,start,end,  left,right,sepval,tmp,tmpe,tmps) {
  100.     # handle two-element case explicitly for a tiny speedup
  101.     if ((end - start) == 1) {
  102.     if (Arr[tmps = k[start]] > Arr[tmpe = k[end]]) {
  103.         k[start] = tmpe
  104.         k[end] = tmps
  105.     }
  106.     return
  107.     }
  108.     # Make sure comparisons act on these as numbers
  109.     left = start+0
  110.     right = end+0
  111.     sepval = Arr[k[int((left + right) / 2)]]
  112.     # Make every element <= sepval be to the left of every element > sepval
  113.     while (left < right) {
  114.     while (Arr[k[left]] < sepval)
  115.         left++
  116.     while (Arr[k[right]] > sepval)
  117.         right--
  118.     if (left < right) {
  119.         tmp = k[left]
  120.         k[left++] = k[right]
  121.         k[right--] = tmp
  122.     }
  123.     }
  124.     if (left == right)
  125.     if (Arr[k[left]] < sepval)
  126.         left++
  127.     else
  128.         right--
  129.     if (start < right)
  130.     qsortSegment(Arr,k,start,right)
  131.     if (left < end)
  132.     qsortSegment(Arr,k,left,end)
  133. }
  134.  
  135. # Arr[] is an array of values with arbitrary indices.
  136. # k[] is returned with numeric indices 1..n.
  137. # The values in k are the indices of Arr[],
  138. # ordered so that if Arr[] is stepped through
  139. # in the order Arr[k[1]] .. Arr[k[n]], it will be stepped
  140. # through in order of the values of its indices.
  141. # The return value is the number of elements in the arrays (n).
  142. # If the indexes are numeric, Numeric should be true, so that they can be
  143. # compared as such rather than as strings.  Numeric indexes do not have to be
  144. # contiguous.
  145. function qsortByArbIndex(Arr,k,Numeric,  ArrInd,ElNum) {
  146.     ElNum = 0
  147.     if (Numeric)
  148.     # Indexes do not preserve numeric type, so must be forced
  149.     for (ArrInd in Arr)
  150.         k[++ElNum] = ArrInd+0
  151.     else
  152.     for (ArrInd in Arr)
  153.         k[++ElNum] = ArrInd
  154.     qsortNumIndByValue(k,1,ElNum)
  155.     return ElNum
  156. }
  157.  
  158. # Arr is an array of elements with contiguous numeric indexes to be sorted
  159. # by value.
  160. # start and end are the starting and ending indexes of the range to be sorted.
  161. function qsortNumIndByValue(Arr,start,end,  left,right,sepval,tmp,tmpe,tmps) {
  162.     # handle two-element case explicitly for a tiny speedup
  163.     if ((start - end) == 1) {
  164.     if ((tmps = Arr[start]) > (tmpe = Arr[end])) {
  165.         Arr[start] = tmpe
  166.         Arr[end] = tmps
  167.     }
  168.     return
  169.     }
  170.     left = start+0
  171.     right = end+0
  172.     sepval = Arr[int((left + right) / 2)]
  173.     while (left < right) {
  174.     while (Arr[left] < sepval)
  175.         left++
  176.     while (Arr[right] > sepval)
  177.         right--
  178.     if (left <= right) {
  179.         tmp = Arr[left]
  180.         Arr[left++] = Arr[right]
  181.         Arr[right--] = tmp
  182.     }
  183.     }
  184.     if (start < right)
  185.     qsortNumIndByValue(Arr,start,right)
  186.     if (left < end)
  187.     qsortNumIndByValue(Arr,left,end)
  188. }
  189.  
  190. ### End qsort routines
  191. ### Start of ProcArgs library
  192. # @(#) ProcArgs 1.11 96/12/08
  193. # 92/02/29 john h. dubois iii (john@armory.com)
  194. # 93/07/18 Added "#" arg type
  195. # 93/09/26 Do not count -h against MinArgs
  196. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  197. #          Removed meaning of "+" or "-" by itself.
  198. # 94/03/08 Added & option and *()< option types.
  199. # 94/04/02 Added NoRCopt to Opts()
  200. # 94/06/11 Mark numeric variables as such.
  201. # 94/07/08 Opts(): Do not require any args if h option is given.
  202. # 95/01/22 Record options given more than once.  Record option num in argv.
  203. # 95/06/08 Added ExclusiveOptions().
  204. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  205. #          Expand $VARNAME at the start of its filenames.
  206. #          Let varname=0 and -option- turn off an option.
  207. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  208. #          of the vars should be searched for in the environment.
  209. #          Check for duplicate rcfiles.
  210. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  211. #          now return various negatives values on error, not just -1, and
  212. #          Opts() may set Err to various positive values, not just 1.
  213. #          Added AllowUnrecOpt.
  214. # 96/05/23 Check type given for & option
  215. # 96/06/15 Re-port to awk
  216. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  217. #          used by other functions.
  218. # 96/10/15 Added OptChars
  219. # 96/11/01 Added exOpts arg to Opts()
  220. # 96/11/16 Added ; type
  221. # 96/12/08 Added Opt2Set() & Opt2Sets()
  222. # 96/12/27 Added CmdLineOpt()
  223.  
  224. # optlist is a string which contains all of the possible command line options.
  225. # A character followed by certain characters indicates that the option takes
  226. # an argument, with type as follows:
  227. # :    String argument
  228. # ;    Non-empty string argument
  229. # *    Floating point argument
  230. # (    Non-negative floating point argument
  231. # )    Positive floating point argument
  232. # #    Integer argument
  233. # <    Non-negative integer argument
  234. # >    Positive integer argument
  235. # The only difference the type of argument makes is in the runtime argument
  236. # error checking that is done.
  237.  
  238. # The & option is a special case used to get numeric options without the
  239. # user having to give an option character.  It is shorthand for [-+.0-9].
  240. # If & is included in optlist and an option string that begins with one of
  241. # these characters is seen, the value given to "&" will include the first
  242. # char of the option.  & must be followed by a type character other than ":"
  243. # or ";".
  244. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  245.  
  246. # Strings in argv[] which begin with "-" or "+" are taken to be
  247. # strings of options, except that a string which consists solely of "-"
  248. # or "+" is taken to be a non-option string; like other non-option strings,
  249. # it stops the scanning of argv and is left in argv[].
  250. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  251. # If an option takes an argument, the argument may either immediately
  252. # follow it or be given separately.
  253. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  254. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  255. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  256. # this feature had a flaw that caused problems in some cases.  See the OptChars
  257. # parameter to explicitly set the option-specifier characters.
  258.  
  259. # If an option that does not take an argument is given,
  260. # an index with its name is created in Options and its value is set to the
  261. # number of times it occurs in argv[].
  262.  
  263. # If an option that does take an argument is given, an index with its name is
  264. # created in Options and its value is set to the value of the argument given
  265. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  266. # If an option that takes an argument is given more than once,
  267. # Options[option-name,"count"] is incremented, and the value is assigned to
  268. # the index (option-name,instance) where instance is 2 for the second occurance
  269. # of the option, etc.
  270. # In other words, the first time an option with a value is encountered, the
  271. # value is assigned to an index consisting only of its name; for any further
  272. # occurances of the option, the value index has an extra (count) dimension.
  273.  
  274. # The sequence number for each option found in argv[] is stored in
  275. # Options[option-name,"num",instance], where instance is 1 for the first
  276. # occurance of the option, etc.  The sequence number starts at 1 and is
  277. # incremented for each option, both those that have a value and those that
  278. # do not.  Options set from a config file have a value of 0 assigned to this.
  279.  
  280. # Options and their arguments are deleted from argv.
  281. # Note that this means that there may be gaps left in the indices of argv[].
  282. # If compress is nonzero, argv[] is packed by moving its elements so that
  283. # they have contiguous integer indices starting with 0.
  284. # Option processing will stop with the first unrecognized option, just as
  285. # though -- was given except that unlike -- the unrecognized option will not be
  286. # removed from ARGV[].  Normally, an error value is returned in this case.
  287. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  288. # be found, so the number of remaining arguments is returned instead.
  289. # If OptChars is not a null string, it is the set of characters that indicate
  290. # that an argument is an option string if the string begins with one of the
  291. # characters.  A string consisting solely of two of the same option-indicator
  292. # characters stops the scanning of argv[].  The default is "-+".
  293. # argv[0] is not examined.
  294. # The number of arguments left in argc is returned.
  295. # If an error occurs, the global string OptErr is set to an error message
  296. # and a negative value is returned.
  297. # Current error values:
  298. # -1: option that required an argument did not get it.
  299. # -2: argument of incorrect type supplied for an option.
  300. # -3: unrecognized (invalid) option.
  301. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  302. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  303. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  304. {
  305. # ArgNum is the index of the argument being processed.
  306. # ArgsLeft is the number of arguments left in argv.
  307. # Arg is the argument being processed.
  308. # ArgLen is the length of the argument being processed.
  309. # ArgInd is the position of the character in Arg being processed.
  310. # Option is the character in Arg being processed.
  311. # Pos is the position in OptList of the option being processed.
  312. # NumOpt is true if a numeric option may be given.
  313.     ArgsLeft = argc
  314.     NumOpt = index(OptList,"&")
  315.     OptionNum = 0
  316.     if (OptChars == "")
  317.     OptChars = "-+"
  318.     while (OptChars != "") {
  319.     c = substr(OptChars,1,1)
  320.     OptChars = substr(OptChars,2)
  321.     OptCharSet[c]
  322.     OptTerm[c c]
  323.     }
  324.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  325.     Arg = argv[ArgNum]
  326.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  327.         break    # Not an option; quit
  328.     if (Arg in OptTerm) {
  329.         delete argv[ArgNum]
  330.         ArgsLeft--
  331.         break
  332.     }
  333.     ArgLen = length(Arg)
  334.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  335.         Option = substr(Arg,ArgInd,1)
  336.         if (NumOpt && Option ~ /[-+.0-9]/) {
  337.         # If this option is a numeric option, make its flag be & and
  338.         # its option string flag position be the position of & in
  339.         # the option string.
  340.         Option = "&"
  341.         Pos = NumOpt
  342.         # Prefix Arg with a char so that ArgInd will point to the
  343.         # first char of the numeric option.
  344.         Arg = "&" Arg
  345.         ArgLen++
  346.         }
  347.         # Find position of flag in option string, to get its type (if any).
  348.         # Disallow & as literal flag.
  349.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  350.         if (AllowUnrecOpt) {
  351.             Escape = 1
  352.             break
  353.         }
  354.         else {
  355.             OptErr = "Invalid option: " specGiven Option
  356.             return -3
  357.         }
  358.         }
  359.  
  360.         # Find what the value of the option will be if it takes one.
  361.         # NeedNextOpt is true if the option specifier is the last char of
  362.         # this arg, which means that if the option requires a value it is
  363.         # the next arg.
  364.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  365.         if (GotValue = ArgNum + 1 < argc)
  366.             Value = argv[ArgNum+1]
  367.         }
  368.         else {    # Value is included with option
  369.         Value = substr(Arg,ArgInd + 1)
  370.         GotValue = 1
  371.         }
  372.  
  373.         if (HadValue = AssignVal(Option,Value,Options,
  374.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  375.         specGiven)) {
  376.         if (HadValue < 0)    # error occured
  377.             return HadValue
  378.         if (HadValue == 2)
  379.             ArgInd++    # Account for the single-char value we used.
  380.         else {
  381.             if (NeedNextOpt) {    # option took next arg as value
  382.             delete argv[++ArgNum]
  383.             ArgsLeft--
  384.             }
  385.             break    # This option has been used up
  386.         }
  387.         }
  388.     }
  389.     if (Escape)
  390.         break
  391.     # Do not delete arg until after processing of it, so that if it is not
  392.     # recognized it can be left in ARGV[].
  393.     delete argv[ArgNum]
  394.     ArgsLeft--
  395.     }
  396.     if (compress != 0) {
  397.     dest = 1
  398.     src = argc - ArgsLeft + 1
  399.     for (count = ArgsLeft - 1; count; count--) {
  400.         ARGV[dest] = ARGV[src]
  401.         dest++
  402.         src++
  403.     }
  404.     }
  405.     return ArgsLeft
  406. }
  407.  
  408. # Assignment to values in Options[] occurs only in this function.
  409. # Option: Option specifier character.
  410. # Value: Value to be assigned to option, if it takes a value.
  411. # Options[]: Options array to return values in.
  412. # ArgType: Argument type specifier character.
  413. # GotValue: Whether any value is available to be assigned to this option.
  414. # Name: Name of option being processed.
  415. # OptionNum: Number of this option (starting with 1) if set in argv[],
  416. #     or 0 if it was given in a config file or in the environment.
  417. # SingleOpt: true if the value (if any) that is available for this option was
  418. #     given as part of the same command line arg as the option.  Used only for
  419. #     options from the command line.
  420. # specGiven is the option specifier character use, if any (e.g. - or +),
  421. # for use in error messages.
  422. # Global variables: OptErr
  423. # Return value: negative value on error, 0 if option did not require an
  424. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  425. # the arg.
  426. # Current error values:
  427. # -1: Option that required an argument did not get it.
  428. # -2: Value of incorrect type supplied for option.
  429. # -3: Bad type given for option &
  430. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  431. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  432.     # If option takes a value...    [
  433.     NumTypes = "*()#<>]"
  434.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  435.     OptErr = "Bad type given for & option"
  436.     return -3
  437.     }
  438.  
  439.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  440.     if (!GotValue) {
  441.         if (Name != "")
  442.         OptErr = "Variable requires a value -- " Name
  443.         else
  444.         OptErr = "option requires an argument -- " Option
  445.         return -1
  446.     }
  447.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  448.         OptErr = Err
  449.         return -2
  450.     }
  451.     # Mark this as a numeric variable; will be propogated to Options[] val.
  452.     if (ArgType != ":" && ArgType != ";")
  453.         Value += 0
  454.     if ((Instance = ++Options[Option,"count"]) > 1)
  455.         Options[Option,Instance] = Value
  456.     else
  457.         Options[Option] = Value
  458.     }
  459.     # If this is an environ or rcfile assignment & it was given a value...
  460.     else if (!OptionNum && Value != "") {
  461.     UsedValue = 1
  462.     # If the value is "0" or "-" and this is the first instance of it,
  463.     # do not set Options[Option]; this allows an assignment in an rcfile to
  464.     # turn off an option (for the simple "Option in Options" test) in such
  465.     # a way that it cannot be turned on in a later file.
  466.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  467.         Instance = 1
  468.     else
  469.         Instance = ++Options[Option]
  470.     # Save the value even though this is a flag
  471.     Options[Option,Instance] = Value
  472.     }
  473.     # If this is a command line flag and has a - following it in the same arg,
  474.     # it is being turned off.
  475.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  476.     UsedValue = 2
  477.     if (Option in Options)
  478.         Instance = ++Options[Option]
  479.     else
  480.         Instance = 1
  481.     Options[Option,Instance]
  482.     }
  483.     # If this is a flag assignment without a value, increment the count for the
  484.     # flag unless it was turned off.  The indicator for a flag being turned off
  485.     # is that the flag index has not been set in Options[] but it has an
  486.     # instance count.
  487.     else if (Option in Options || !((Option,1) in Options))
  488.     # Increment number of times this flag seen; will inc null value to 1
  489.     Instance = ++Options[Option]
  490.     Options[Option,"num",Instance] = OptionNum
  491.     return UsedValue
  492. }
  493.  
  494. # Option is the option letter
  495. # Value is the value being assigned
  496. # Name is the var name of the option, if any
  497. # ArgType is one of:
  498. # :    String argument
  499. # ;    Non-null string argument
  500. # *    Floating point argument
  501. # (    Non-negative floating point argument
  502. # )    Positive floating point argument
  503. # #    Integer argument
  504. # <    Non-negative integer argument
  505. # >    Positive integer argument
  506. # specGiven is the option specifier character use, if any (e.g. - or +),
  507. # for use in error messages.
  508. # Returns null on success, err string on error
  509. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  510.     if (ArgType == ":")
  511.     return ""
  512.     if (ArgType == ";") {
  513.     if (Value == "")
  514.         Err = "must be a non-empty string"
  515.     }
  516.     # A number begins with optional + or -, and is followed by a string of
  517.     # digits or a decimal with digits before it, after it, or both
  518.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  519.     Err = "must be a number"
  520.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  521.     Err = "may not include a fraction"
  522.     else if (ArgType ~ "[()<>]" && Value < 0)
  523.     Err = "may not be negative"
  524.     # (
  525.     else if (ArgType ~ "[)>]" && Value == 0)
  526.     Err = "must be a positive number"
  527.     if (Err != "") {
  528.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  529.     if (Name != "")
  530.         return ErrStr "variable " substr(Name,1,1) " " Err
  531.     else {
  532.         if (Option == "&")
  533.         Option = Value
  534.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  535.     }
  536.     }
  537.     else
  538.     return ""
  539. }
  540.  
  541. # Note: only the above functions are needed by ProcArgs.
  542. # The rest of these functions call ProcArgs() and also do other
  543. # option-processing stuff.
  544.  
  545. # Opts: Process command line arguments.
  546. # Opts processes command line arguments using ProcArgs()
  547. # and checks for errors.  If an error occurs, a message is printed
  548. # and the program is exited.
  549. #
  550. # Input variables:
  551. # Name is the name of the program, for error messages.
  552. # Usage is a usage message, for error messages.
  553. # OptList the option description string, as used by ProcArgs().
  554. # MinArgs is the minimum number of non-option arguments that this
  555. # program should have, non including ARGV[0] and +h.
  556. # If the program does not require any non-option arguments,
  557. # MinArgs should be omitted or given as 0.
  558. # rcFiles, if given, is a colon-seprated list of filenames to read for
  559. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  560. # by the value of the environment variable HOME.  If a filename begins with
  561. # $, the part from the character after the $ up until (but not including)
  562. # the first character not in [a-zA-Z0-9_] will be searched for in the
  563. # environment; if found its value will be substituted, if not the filename will
  564. # be discarded.
  565. # rcfiles are read in the order given.
  566. # Values given in them will not override values given on the command line,
  567. # and values given in later files will not override those set in earlier
  568. # files, because AssignVal() will store each with a different instance index.
  569. # The first instance of each variable, either on the command line or in an
  570. # rcfile, will be stored with no instance index, and this is the value
  571. # normally used by programs that call this function.
  572. # VarNames is a comma-separated list of variable names to map to options,
  573. # in the same order as the options are given in OptList.
  574. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  575. # searched for in the environment.  If set to -1, all values will be searched
  576. # for in the environment.  Values given in the environment will override
  577. # those given in the rcfiles but not those given on the command line.
  578. # NoRCopt, if given, is an additional letter option that if given on the
  579. # command line prevents the rcfiles from being read.
  580. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  581. # ExclusiveOptions() for a description of exOpts.
  582. # Special options:
  583. # If x is made an option and is given, some debugging info is output.
  584. # h is assumed to be the help option.
  585.  
  586. # Global variables:
  587. # The command line arguments are taken from ARGV[].
  588. # The arguments that are option specifiers and values are removed from
  589. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  590. # The number of elements in ARGV[] should be in ARGC.
  591. # After processing, ARGC is set to the number of elements left in ARGV[].
  592. # The option values are put in Options[].
  593. # On error, Err is set to a positive integer value so it can be checked for in
  594. # an END block.
  595. # Return value: The number of elements left in ARGV is returned.
  596. # Must keep OptErr global since it may be set by InitOpts().
  597. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  598. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  599.     if (MinArgs == "")
  600.     MinArgs = 0
  601.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  602.     optChars)
  603.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  604.     if (ArgsLeft >= 0) {
  605.         OptErr = "Not enough arguments"
  606.         Err = 4
  607.     }
  608.     else
  609.         Err = -ArgsLeft
  610.     printf "%s: %s.\nUse -h for help.\n%s\n",
  611.     Name,OptErr,Usage > "/dev/stderr"
  612.     exit 1
  613.     }
  614.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  615.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  616.     {
  617.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  618.     Err = -e
  619.     exit 1
  620.     }
  621.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  622.     {
  623.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  624.     Err = 1
  625.     exit 1
  626.     }
  627.     return ArgsLeft
  628. }
  629.  
  630. # ReadConfFile(): Read a file containing var/value assignments, in the form
  631. # <variable-name><assignment-char><value>.
  632. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  633. # line and whitespace between the variable name and the assignment character) 
  634. # is stripped.  Lines that do not contain an assignment operator or which
  635. # contain a null variable name are ignored, other than possibly being noted in
  636. # the return value.  If more than one assignment is made to a variable, the
  637. # first assignment is used.
  638. # Input variables:
  639. # File is the file to read.
  640. # Comment is the line-comment character.  If it is found as the first non-
  641. #     whitespace character on a line, the line is ignored.
  642. # Assign is the assignment string.  The first instance of Assign on a line
  643. #     separates the variable name from its value.
  644. # If StripWhite is true, whitespace around the value (whitespace between the
  645. #     assignment char and trailing whitespace on the line) is stripped.
  646. # VarPat is a pattern that variable names must match.  
  647. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  648. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  649. #     a line; no assignment operator is needed.  These variables are set in
  650. #     the output array with a null value.  Lines containing nothing but
  651. #     whitespace are still ignored.
  652. # Output variables:
  653. # Values[] contains the assignments, with the indexes being the variable names
  654. #     and the values being the assigned values.
  655. # Lines[] contains the line number that each variable occured on.  A flag set
  656. #     is record by giving it an index in Lines[] but not in Values[].
  657. # Return value:
  658. # If any errors occur, a string consisting of descriptions of the errors
  659. # separated by newlines is returned.  In no case will the string start with a
  660. # numeric value.  If no errors occur,  the number of lines read is returned.
  661. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  662. FlagsOK,
  663. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  664.     if (Comment != "")
  665.     Comment = "^" Comment
  666.     AssignLen = length(Assign)
  667.     if (VarPat == "")
  668.     VarPat = "."    # null varname not allowed
  669.     while ((Status = (getline Line < File)) == 1) {
  670.     LineNum++
  671.     sub("^[ \t]+","",Line)
  672.     if (Line == "")        # blank line
  673.         continue
  674.     if (Comment != "" && Line ~ Comment)
  675.         continue
  676.     if (Pos = index(Line,Assign)) {
  677.         Var = substr(Line,1,Pos-1)
  678.         Val = substr(Line,Pos+AssignLen)
  679.         if (StripWhite) {
  680.         sub("^[ \t]+","",Val)
  681.         sub("[ \t]+$","",Val)
  682.         }
  683.     }
  684.     else {
  685.         Var = Line    # If no value, var is entire line
  686.         Val = ""
  687.     }
  688.     if (!FlagsOK && Val == "") {
  689.         Errs = Errs \
  690.         sprintf("\nBad assignment on line %d of file %s: %s",
  691.         LineNum,File,Line)
  692.         continue
  693.     }
  694.     sub("[ \t]+$","",Var)
  695.     if (Var !~ VarPat) {
  696.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  697.         LineNum,File,Var)
  698.         continue
  699.     }
  700.     if (!(Var in Lines)) {
  701.         Lines[Var] = LineNum
  702.         if (Pos)
  703.         Values[Var] = Val
  704.     }
  705.     }
  706.     if (Status)
  707.     Errs = Errs "\nCould not read file " File
  708.     close(File)
  709.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  710. }
  711.  
  712. # Variables:
  713. # Data is stored in Options[].
  714. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  715. # Global vars:
  716. # Sets OptErr.  Uses ENVIRON[].
  717. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  718. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  719. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  720. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  721.     split("",filesRead,"")    # make awk know this is an array
  722.     NumVars = split(VarNames,Vars,",")
  723.     TypesInd = Ret = 0
  724.     if (EnvSearch == -1)
  725.     EnvSearch = NumVars
  726.     for (i = 1; i <= NumVars; i++) {
  727.     Var = Vars[i]
  728.     CharOpt = substr(OptList,++TypesInd,1)
  729.     if (CharOpt ~ "^[:;*()#<>&]$")
  730.         CharOpt = substr(OptList,++TypesInd,1)
  731.     Map[Var] = CharOpt
  732.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  733.     # Do not overwrite entries from environment
  734.     if (i <= EnvSearch && Var in ENVIRON &&
  735.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  736.         return Err
  737.     }
  738.  
  739.     numrcFiles = split(rcFiles,fNames,":")
  740.     for (i = 1; i <= numrcFiles; i++) {
  741.     rcFile = fNames[i]
  742.     if (rcFile ~ "^~/")
  743.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  744.     else if (rcFile ~ /^\$/) {
  745.         rcFile = substr(rcFile,2)
  746.         match(rcFile,"^[a-zA-Z0-9_]*")
  747.         envvar = substr(rcFile,1,RLENGTH)
  748.         if (envvar in ENVIRON)
  749.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  750.         else
  751.         continue
  752.     }
  753.     if (rcFile in filesRead)
  754.         continue
  755.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  756.     # may be the same
  757.     filesRead[rcFile]
  758.     if ("x" in Options)
  759.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  760.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  761.     if (retStr > 0)
  762.         READ_RCFILE = 1
  763.     else if (ret != "") {
  764.         OptErr = retStr
  765.         Ret = -1
  766.     }
  767.     for (Var in Lines)
  768.         if (Var in Map) {
  769.         if ((Err = AssignVal(Map[Var],
  770.         Var in Values ? Values[Var] : "",Options,Types[Var],
  771.         Var in Values,Var,0)) < 0)
  772.             return Err
  773.         }
  774.         else {
  775.         OptErr = sprintf(\
  776.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  777.         Lines[Var],rcFile)
  778.         Ret = -1
  779.         }
  780.     }
  781.  
  782.     if ("x" in Options)
  783.     for (Var in Map)
  784.         if (Map[Var] in Options)
  785.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  786.         "/dev/stderr"
  787.         else
  788.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  789.     return Ret
  790. }
  791.  
  792. # OptSets is a semicolon-separated list of sets of option sets.
  793. # Within a list of option sets, the option sets are separated by commas.  For
  794. # each set of sets, if any option in one of the sets is in Options[] AND any
  795. # option in one of the other sets is in Options[], an error string is returned.
  796. # If no conflicts are found, nothing is returned.
  797. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  798. # the exclusions presented by the first set of sets (ab,def,g) if:
  799. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  800. # (a or b is in Options[]) AND (g is in Options) OR
  801. # (d, e, or f is in Options[]) AND (g is in Options)
  802. # An error will be returned due to the exclusions presented by the second set
  803. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  804. # todo: make options given on command line unset options given in config file
  805. # todo: that they conflict with.
  806. function ExclusiveOptions(OptSets,Options,
  807. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  808. SetNum,OSetNum) {
  809.     NumSetSets = split(OptSets,SetSets,";")
  810.     # For each set of sets...
  811.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  812.     # NumSets is the number of sets in this set of sets.
  813.     NumSets = split(SetSets[SetSet],Sets,",")
  814.     # For each set in a set of sets except the last...
  815.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  816.         s1 = Sets[SetNum]
  817.         L1 = length(s1)
  818.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  819.         # If any of the options in this set was given, check whether
  820.         # any of the options in the other sets was given.  Only check
  821.         # later sets since earlier sets will have already been checked
  822.         # against this set.
  823.         if ((c1 = substr(s1,Pos1,1)) in Options)
  824.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  825.             s2 = Sets[OSetNum]
  826.             L2 = length(s2)
  827.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  828.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  829.                 ErrStr = ErrStr "\n"\
  830.                 sprintf("Cannot give both %s and %s options.",
  831.                 c1,c2)
  832.             }
  833.     }
  834.     }
  835.     if (ErrStr != "")
  836.     return substr(ErrStr,2)
  837.     return ""
  838. }
  839.  
  840. # The value of each instance of option Opt that occurs in Options[] is made an
  841. # index of Set[].
  842. # The return value is the number of instances of Opt in Options.
  843. function Opt2Set(Options,Opt,Set,  count) {
  844.     if (!(Opt in Options))
  845.     return 0
  846.     Set[Options[Opt]]
  847.     count = Options[Opt,"count"]
  848.     for (; count > 1; count--)
  849.     Set[Options[Opt,count]]
  850.     return count
  851. }
  852.  
  853. # The value of each instance of option Opt that occurs in Options[] that
  854. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  855. # Other values are made indexes of Set[].
  856. # The return value is the number of instances of Opt in Options.
  857. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  858.     ret = Opt2Set(Options,Opt,aSet)
  859.     for (value in aSet)
  860.     if (substr(value,1,1) == "!")
  861.         nSet[substr(value,2)]
  862.     else
  863.         Set[value]
  864.     return ret
  865. }
  866.  
  867. # Returns true if option Opt was given on the command line.
  868. function CmdLineOpt(Options,Opt,  i) {
  869.     for (i = 1; (Opt,"num",i) in Options; i++)
  870.     if (Options[Opt,"num",i] != 0)
  871.         return 1
  872.     return 0
  873. }
  874. ### End of ProcArgs library
  875.